package com.yilin.tms.truck.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.StringUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.system.param.CommTruckType;
import com.yilin.tms.core.entity.system.param.TruckEnergyType;
import com.yilin.tms.core.entity.system.param.TruckPlate;
import com.yilin.tms.core.entity.system.param.TruckType;
import com.yilin.tms.core.entity.truck.TransportLicense;
import com.yilin.tms.core.entity.truck.TravelLicense;
import com.yilin.tms.core.entity.truck.TruckVehicle;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.organize.Organize;
import com.yilin.tms.core.remote.IGpsRemote;
import com.yilin.tms.core.remote.ISystemRemote;
import com.yilin.tms.core.remote.IUserRemote;
import com.yilin.tms.truck.service.ITransportLicenseService;
import com.yilin.tms.truck.service.ITravelLicenseService;
import com.yilin.tms.truck.mapper.TruckVehicleMapper;
import com.yilin.tms.truck.service.ITruckVehicleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.*;


/**
 * 车辆服务
 *
 * @author zhangjinyuan
 * @date 2022/10/24
 */
@Service
@Transactional
public class TruckVehicleService extends ServiceImpl<TruckVehicleMapper, TruckVehicle> implements ITruckVehicleService {

    @Resource
    ITravelLicenseService travelLicenseService;
    @Resource
    ITransportLicenseService transportLicenseService;

    @Resource
    TruckVehicleMapper truckVehicleMapper;

    @Resource
    IUserRemote userRemote;
    @Resource
    ISystemRemote systemRemote;
    @Resource
    IGpsRemote gpsRemote;

    /**
     * 车辆找查：根据驾驶员获取车辆
     */
    @Override
    public List<TruckVehicle> getVehicleListByDriverId(String driverId) {
        return truckVehicleMapper.getVehicleListByTruckUserId(driverId);
    }

    /**
     * 车辆找查：车牌号查找
     */
    @Override
    public TruckVehicle getVehicleByNo(String trackNo) {
        return truckVehicleMapper.selectOne(new QueryWrapper<TruckVehicle>().eq("track_no", trackNo));
    }

    /**
     * 车辆找查：获取省级运管未创建数据车辆
     */
    @Override
    public List<TruckVehicle> getErrorTmsVehicle() {
        QueryWrapper<TruckVehicle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tms_truck_data_state", TruckVehicle.TmsTruckDataState.wait);
        queryWrapper.or().eq("tms_truck_data_state", TruckVehicle.TmsTruckDataState.error);
        return truckVehicleMapper.selectList(queryWrapper);
    }

    /**
     * 车辆找查：获取组织全部车辆
     */
    @Override
    public List<TruckVehicle> getVehicleListByOrganizeId(String organizeId, TruckVehicle query) {
        List<TruckVehicle> vehicleList = truckVehicleMapper.getVehicleListByOrganizeId(organizeId, query);
//        return setEquipmentInfo(vehicleList);
        return vehicleList;
    }

    @Override
    public List<TruckVehicle> getUnUsedVehicleListByOrganizeId(String organizeId) {
        QueryWrapper<TruckVehicle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("truck_status", TruckVehicle.TruckStatus.unused);
        return truckVehicleMapper.selectList(queryWrapper);
    }

    @Override
    public Long getOrganzieByListCount(Organize organize) {
        QueryWrapper<TruckVehicle> queryWrapper = new QueryWrapper<>();
        if (organize.getUserType() != UserType.platformUser && organize.getUserType() != UserType.adminUser) {
            queryWrapper.and(wrapper ->
                    wrapper.eq("organize_id", organize.getId())
                            .or()
                            .eq("superior_plat_id", organize.getSuperiorPlatOrganizeId())
            );
        }
        return truckVehicleMapper.selectCount(queryWrapper);
    }


    /**
     * 获取车辆分页
     */
    @Override
    public PageData<TruckVehicle> getTruckVehiclePage(Account loginUser, TruckVehicle query, Integer page, Integer limit) {
        PageData<TruckVehicle> pageQuery = new PageData<>(page, limit);
        PageData<TruckVehicle> vehiclePage = truckVehicleMapper.getTruckVehiclePage(pageQuery, loginUser, query);
        vehiclePage.setList(setEquipmentInfo(vehiclePage.getList()));
        return vehiclePage;
    }

    /**
     * 车辆找查：ETC未备案车辆
     */
    @Override
    public List<TruckVehicle> getEtcNoKeepTruck() {
        QueryWrapper<TruckVehicle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("etc_keep_status", TruckVehicle.EtcKeepStatus.none);
        queryWrapper.lt("etc_keep_count", 3);
        return truckVehicleMapper.selectList(queryWrapper);
    }


    ////设置好运宝设备信息
    private List<TruckVehicle> setEquipmentInfo(List<TruckVehicle> vehicleList) {
        if (vehicleList == null || vehicleList.size() == 0) return vehicleList;
//        List<String> stringList = ArrayUtil.fieldNoRepeatAdd(vehicleList, obj -> {
//            if (obj.getTruckGpsType() != VehicleGps.TruckGpsType.hyb) return null;
//            return obj.getGpsDeviceId();
//        });
//        if (stringList.size() > 0) {
//            String platId = ArrayUtil.first(vehicleList).getPlatId();
//            List<EquipmentInfo> infoList = ParamUtil.isSuccess(gpsRemote.getTrackDeviceInfos(platId, String.join(",", stringList)));
//            for (TruckVehicle truckVehicle : vehicleList) {
//                if (truckVehicle.getTruckGpsType() == VehicleGps.TruckGpsType.hyb && truckVehicle.getGpsDeviceId() != null) {
//                    EquipmentInfo info = ArrayUtil.getBy(infoList, obj -> obj.getDevice().equals(truckVehicle.getGpsDeviceId()));
//                    truckVehicle.setEquipmentInfo(info);
//                }
//            }
//        }
        return vehicleList;
    }


    //-----------------------------------------------保存区-------------------------------------------

    /**
     * 保存车辆
     */
    @Override
    public void saveTruckVehicle(Account loginUser, TruckVehicle truckVehicle, TravelLicense travelLicense, TransportLicense transportLicense) {
        Organize organize = ParamUtil.isSuccess(userRemote.getOrganizeById(loginUser.getOrganizeId()));
//        CommTruckType commTruckType = ParamUtil.isSuccess(systemRemote.getCommTruckTypeById(truckVehicle.getCommTruckTypeId()));
        TruckEnergyType energyType = ParamUtil.isSuccess(systemRemote.getTruckEnergyById(truckVehicle.getTruckEnergyTypeId()));
        TruckType truckType = ParamUtil.isSuccess(systemRemote.getTruckTypeById(truckVehicle.getTruckTypeId()));
        TruckPlate truckPlate = ParamUtil.isSuccess(systemRemote.getTruckPlateById(truckVehicle.getCardPlateId()));
        // #### 设置基本信息
        truckVehicle.setOrganizeId(organize.getId());
        truckVehicle.setOrganizeName(organize.getOrganizeName());
        truckVehicle.setSuperiorPlatId(organize.getSuperiorPlatOrganizeId());
        truckVehicle.setSuperiorPlatName(organize.getSuperiorPlatOrganizeName());
        truckVehicle.setOrganizeLogo(organize.getOrganizeLogo());
        truckVehicle.setOrganizeMonthlyRating(organize.getMonthlyRating());
        truckVehicle.setOrganizeMemberTypeName(organize.getMemberTypeName());
        truckVehicle.setManageUserId(loginUser.getId());
        truckVehicle.setManageUserName(loginUser.getName());
        truckVehicle.setManageUserAvatar(loginUser.getAvatar());
        truckVehicle.setManageUserPhone(loginUser.getPhone());
//        truckVehicle.setCommTruckTypeMatchRank(commTruckType.getRobMatchRank());
//        truckVehicle.setCommTruckTypeName(commTruckType.getName());
        truckVehicle.setTruckEnergyTypeName(energyType.getName());
        truckVehicle.setTruckEnergyTypeCode(energyType.getCode());
        truckVehicle.setTruckTypeName(truckType.getName());
        truckVehicle.setTruckTypeCode(truckType.getCode());
        truckVehicle.setCardPlateName(truckPlate.getName());
        truckVehicle.setCardPlateCode(truckPlate.getCode());
        truckVehicle.setVehicleWeight(travelLicense.getVehicleWeight());
        truckVehicle.setLoadingWeight(travelLicense.getLoadingWeight());
        //赋值
        if (truckVehicle.getTruckStatus() == null) truckVehicle.setTruckStatus(TruckVehicle.TruckStatus.unused);
        // #### 检查车牌号
        TruckVehicle oldTruckVehicle = getOne(new QueryWrapper<TruckVehicle>().eq("tractor_no", truckVehicle.getTrackNo()));
        if (oldTruckVehicle != null && (truckVehicle.getId() == null || !oldTruckVehicle.getId().equals(truckVehicle.getId()))) {
            ParamUtil.notEquals("平台已存在该车牌号", oldTruckVehicle.getId(), truckVehicle.getId());
        }
        //#### 个人用户如果已完成证件认证并且没有绑定其他车辆，自动绑定
        truckVehicle.setTruckUserId(loginUser.getId());
        truckVehicle.setTruckUserAvatar(loginUser.getAvatar());
        truckVehicle.setTruckUserPhone(loginUser.getPhone());
        truckVehicle.setTruckUserName(loginUser.getName());
//        if (truckVehicle.getTruckTypeTowingType() != TruckType.TowingType.trailer && loginUser.getOrganType() == OrganType.individual) {
//            DrivingLicense license = ParamUtil.isSuccess(userRemote.getDrivingLicenseByUserId(loginUser.getId()));
//            QualificationCert qualificationCert = ParamUtil.isSuccess(userRemote.getQualificationCertByUserId(loginUser.getId()));
//            boolean authDrivingLicense = license != null && license.getAuthStatus() == AuthStatus.authSuccess;
//            boolean authQualificationCert = truckVehicle.getVehicleWeight() <= 4.5D || (qualificationCert != null && qualificationCert.getAuthStatus() == AuthStatus.authSuccess);
//            boolean canBindNewVehicle = truckVehicleMapper.selectCount(new QueryWrapper<TruckVehicle>().eq("truck_user_id", loginUser.getId())) == 0;
//            if (authDrivingLicense && authQualificationCert && canBindNewVehicle) {
//                truckVehicle.setTruckUserId(loginUser.getId());
//                truckVehicle.setTruckUserAvatar(loginUser.getAvatar());
//                truckVehicle.setTruckUserPhone(loginUser.getPhone());
//                truckVehicle.setTruckUserName(loginUser.getName());
//            }
//        }
        if (StringUtil.isEmpty(truckVehicle.getId())) {
            truckVehicle.setCreateTime(new Date());
            truckVehicle.setAddUserId(loginUser.getId());
            save(truckVehicle);
        } else {
            truckVehicle.setUpdateTime(new Date());
            truckVehicle.setUpdateUserId(loginUser.getId());
            updateById(truckVehicle);
        }
        //保存行驶证
        travelLicense.setVehicleId(truckVehicle.getId());
        travelLicense.setTruckEnergyTypeName(energyType.getName());
        travelLicense.setTruckEnergyTypeCode(energyType.getCode());
        travelLicense.setTruckTypeName(truckType.getName());
        travelLicense.setTruckTypeCode(truckType.getCode());
        travelLicense.setVehicleLong(truckVehicle.getVehicleLong());
        travelLicense.setVehicleWidth(truckVehicle.getVehicleWidth());
        travelLicense.setVehicleHeight(truckVehicle.getVehicleWeight());
        travelLicense.setLoadingWeight(truckVehicle.getLoadingWeight());
        travelLicense.setLoadingWeight(truckVehicle.getLoadingWeight());
        travelLicense.setTruckNo(truckVehicle.getTrackNo());
        travelLicense.setTruckTypeId(truckVehicle.getTruckTypeId());
        travelLicense.setTruckTypeCode(truckVehicle.getTruckTypeCode());
        travelLicense.setTruckTypeName(truckVehicle.getTruckTypeName());
        travelLicense.setTruckEnergyTypeId(truckVehicle.getTruckEnergyTypeId());
        travelLicense.setTruckEnergyTypeCode(truckVehicle.getTruckEnergyTypeCode());
        travelLicense.setTruckEnergyTypeName(truckVehicle.getTruckEnergyTypeName());
        travelLicenseService.saveTravelLicense(loginUser, travelLicense);
        //保存道路运输证
//        if (truckVehicle.getVehicleWeight() > 4.5) {
//            ParamUtil.isNull(transportLicense, "道路运输证为空");
//            transportLicense.setVehicleId(truckVehicle.getId());
//            transportLicense.setVehicleNo(truckVehicle.getTrackNo());
//            transportLicense.setTruckPlateId(truckVehicle.getCardPlateId());
//            transportLicense.setTruckPlateName(truckVehicle.getCardPlateName());
//            transportLicenseService.saveTransportLicense(loginUser, transportLicense);
//        }
//        //####绑定设备号
//        if (truckVehicle.getTruckGpsType() == VehicleGps.TruckGpsType.hyb && truckVehicle.getGpsDeviceId() != null) {
//            if (oldTruckVehicle!=null && !oldTruckVehicle.getGpsDeviceId().equals(truckVehicle.getGpsDeviceId())){
//                ParamUtil.isSuccess(gpsRemote.unBindVehicleDevice(truckVehicle.getPlatId(),
//                        oldTruckVehicle.getGpsDeviceId(), oldTruckVehicle.getTrackNo()));
//            }
//            ParamUtil.isSuccess(gpsRemote.bindVehicleDevice(truckVehicle.getPlatId(),
//                    truckVehicle.getGpsDeviceId(), truckVehicle.getTrackNo()));
//        }

    }

    /**
     * 绑定驾驶员
     */
    @Override
    public void bindTruckUser(Account loginUser, Account truckUser, TruckVehicle truckVehicle, TruckVehicle originalTruckVehicle) {
        //解绑司机原有车辆
        if (originalTruckVehicle != null) {
            originalTruckVehicle.setTruckUserId("");
            originalTruckVehicle.setTruckUserAvatar("");
            originalTruckVehicle.setTruckUserPhone("");
            originalTruckVehicle.setTruckUserName("");
            originalTruckVehicle.setUpdateTime(new Date());
            originalTruckVehicle.setUpdateUserId(loginUser.getId());
            updateById(originalTruckVehicle);
        }
        truckVehicle.setTruckUserId(truckUser.getId());
        truckVehicle.setTruckUserAvatar(truckUser.getAvatar());
        truckVehicle.setTruckUserPhone(truckUser.getPhone());
        truckVehicle.setTruckUserName(truckUser.getName());
        truckVehicle.setUpdateTime(new Date());
        truckVehicle.setUpdateUserId(loginUser.getId());
        updateById(truckVehicle);
    }

    /**
     * 根据公共车辆类型获取空闲的司机
     */
    @Override
    public String[] getPushTruckerIdsByCommTruckTypeIds(String commTruckTypeIds) {
        if (StringUtil.isEmpty(commTruckTypeIds)) {
            return truckVehicleMapper.getTruckUserListByUnused();
        } else {
            //公共车辆类型
            List<CommTruckType> list = ParamUtil.isSuccess(systemRemote.getCommTruckTypeListByIds(commTruckTypeIds.split(",")));
            //获取最小级别的公共车辆类型
            list.sort(Comparator.comparing(CommTruckType::getRobMatchRank));
            CommTruckType commTruckType = ArrayUtil.first(list);
            //用最小匹配级别的车型去获取适应车辆的车主
            return truckVehicleMapper.getTruckUserListByMatchRank(commTruckType.getRobMatchRank());
        }
    }

    /**
     * 获取组织拥有的公共车辆类型
     */
    @Override
    public List<String> getCommTruckTypeIdByOrganizeId(String organizeId) {
        return truckVehicleMapper.getCommTruckTypeIdByOrganId(organizeId);
    }


}
